package com.ma4567.remotecontroller.FileRequest;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ma4567.remotecontroller.MysqlHelper.TableLogManager;
import com.ma4567.remotecontroller.MysqlHelper.TableRequestLog;
import com.ma4567.remotecontroller.RemoteControllerApplication;
import com.ma4567.remotecontroller.ffmpegManager.ffmpegController;
import com.ma4567.remotecontroller.util.File;
import com.ma4567.remotecontroller.util.LocalFileScanner;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.ArrayList;

@CrossOrigin
@RestController
public class FileSearchRequest {
    @RequestMapping(value = "/api/searchFile", method = RequestMethod.GET)
    public String getSearchIndex(HttpServletRequest request,
                                 @RequestParam("cookie") String Cookie,
                                 @RequestParam("path") String path,
                                 @RequestParam("search") String search) throws SQLException {
        ffmpegController.StopStream();
        TableRequestLog.AddLog("Search file: " + search + " at path: " + path, Cookie, request.getRemoteAddr());
        if(!RemoteControllerApplication.userManager.JudgeCookie(Cookie)){//鉴权
            return JSONObject.toJSONString(new FileListRespone(1), SerializerFeature.PrettyFormat);
        }
        else {
            if(!(new java.io.File(path).isDirectory()) && !"Root".equals(path)){
                return JSONObject.toJSONString(new FileListRespone(2), SerializerFeature.PrettyFormat);
            }
            else{
                RemoteControllerApplication.userManager.SetLoggedUserCurrentPath(Cookie, path);

                if(!search.isEmpty()){
                    ArrayList<File> TargetFiles = LocalFileScanner.GetDictoryFile(path);
                    ArrayList<File> Result = new ArrayList<>();

                    search = search.toLowerCase();
                    for(File file : TargetFiles){
                        if(file.FileName.toLowerCase().contains(search)){
                            Result.add(file);
                        }
                    }
                    TableLogManager.AddLog("Search file: " + search + " at path: " + path, Cookie);
                    return JSONObject.toJSONString(new FileListRespone(0, Result), SerializerFeature.PrettyFormat);
                }

                TableLogManager.AddLog("Search file: " + search + " at path: " + path, Cookie);
                return JSONObject.toJSONString(new FileListRespone(0, LocalFileScanner.GetDictoryFile(path)), SerializerFeature.PrettyFormat);
            }
        }
    }
}
